import { Injectable, Optional, SkipSelf } from '@angular/core';
import { combineLatest, BehaviorSubject, Subject } from 'rxjs';
import { auditTime, distinctUntilChanged, map, tap } from 'rxjs/operators';

@Injectable()
export class MenuService {
  mouseEnter$ = new Subject<boolean>();

  open$ = new BehaviorSubject<boolean>(false);
  subMenuOpen$ = new BehaviorSubject<boolean>(false);
  menuOpen$ = combineLatest([this.subMenuOpen$, this.mouseEnter$]).pipe(
    map((value): any => value[0] || value[1]),
    auditTime(5),
    distinctUntilChanged(),
    tap((data: any): void => {
      this.setOpenState(data);
      if (this.menuHostService) {
        this.menuHostService.subMenuOpen$.next(data);
      }
    }),
  );

  constructor(@SkipSelf() @Optional() private menuHostService: MenuService) {}

  setOpenState(value: boolean): void {
    this.open$.next(value);
  }

  setMouseEnterState(value: boolean): void {
    this.mouseEnter$.next(value);
  }
}
